<template>
  <el-dialog
    v-model="visible"
    title="位移数据分析"
    width="70%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <div class="dialog-content">
      <div v-if="warningRanges.length > 0">
        <h4>监测点位移状态监测</h4>
        <div class="warning-grid">
          <div v-for="(range, index) in warningRanges" :key="index" class="grid-item">
            <div class="grid-item-header">
              <span class="level-indicator" :style="{ backgroundColor: range.color }"></span>
              <span class="level-name">{{ range.name }}</span>
            </div>
            <div class="grid-item-body">
              <span class="level-range">{{ range.text }}</span>
              <span v-if="range.count !== null" class="point-count">
                (共 {{ range.count }} 个监测点)
              </span>
              <span v-else class="point-count">
                (正在统计...)
              </span>
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <p>正在加载或没有位移数据...</p>
      </div>

      <el-divider />

      <div>
        <h4>自定义阈值查询</h4>
        <div class="custom-query-form">
          <el-input-number v-model="customThreshold1" :min="0" placeholder="起始阈值" controls-position="right" />
          <span class="separator">至</span>
          <el-input-number v-model="customThreshold2" :min="customThreshold1 ?? 0" placeholder="结束阈值" controls-position="right" />
          <el-button type="primary" @click="handleCustomQuery" :loading="isCustomQueryLoading" :icon="Search">查询</el-button>
        </div>
        
        <div v-if="customQueryTriggered" class="custom-query-result-container">
          <div class="custom-query-header">
            <div class="custom-query-result">
              查询结果：在 {{ customThreshold1 }} 到 {{ customThreshold2 }} {{ displacementData[0]?.unit }} 范围内，共有 <span class="result-count">{{ customQueryRecords.length }}</span> 个监测点。
            </div>
            <el-button 
              type="success" 
              :icon="Download"
              @click="handleExport" 
              :disabled="customQueryRecords.length === 0"
            >
              导出数据
            </el-button>
          </div>
          
          <div class="result-table">
             <el-table :data="customQueryRecords" border style="width: 100%" v-loading="isCustomQueryLoading" height="300">
                <el-table-column prop="data_id" label="编号" width="100" />
                <el-table-column prop="timestamp" label="时间" width="180" />
                <el-table-column prop="x" label="X坐标" />
                <el-table-column prop="y" label="Y坐标" />
                <el-table-column prop="z" label="Z坐标" />
                <el-table-column prop="delta_x" label="ΔX" />
                <el-table-column prop="delta_y" label="ΔY" />
                <el-table-column prop="delta_z" label="ΔZ" />
                <el-table-column prop="vector" label="位移量" />
                <el-table-column prop="velocity" label="速度" />
                <el-table-column prop="acceleration" label="加速度" />
                <el-table-column prop="quality_flag" label="质量标识" width="100" />
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <slot name="footer">
          <el-button @click="close">关闭</el-button>
        </slot>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import axios from "axios";
import { ElMessage } from 'element-plus';
import { Search, Download } from '@element-plus/icons-vue';
import * as XLSX from 'xlsx';

interface Threshold {
  threshold_type: string;
  warning_level: number;
  value: number;
  unit: string;
}

interface WarningRange {
  name: string;
  color: string;
  text: string;
  count: number | null;
}

interface MonitoringRecord {
    data_id: number;
    timestamp: string;
    x: number;
    y: number;
    z: number;
    delta_x: number;
    delta_y: number;
    delta_z: number;
    vector: number;
    velocity: number | null;
    acceleration: number | null;
    quality_flag: string;
}

const visible = ref<boolean>(false);
const displacementData = ref<Threshold[]>([]);
const pointCounts = ref<Record<string, number>>({});
const customThreshold1 = ref<number | undefined>(undefined);
const customThreshold2 = ref<number | undefined>(undefined);
const isCustomQueryLoading = ref<boolean>(false);
const customQueryTriggered = ref<boolean>(false);
const customQueryRecords = ref<MonitoringRecord[]>([]);

const warningRanges = computed<WarningRange[]>(() => {
    if (displacementData.value.length === 0) return [];
    const sortedData = [...displacementData.value].sort((a, b) => a.value - b.value);
    const levels = [
        { name: "蓝色预警", color: "#409EFF" }, { name: "黄色预警", color: "#E6A23C" },
        { name: "橙色预警", color: "#F56C6C" }, { name: "红色预警", color: "#D9001B" },
    ];
    const ranges: WarningRange[] = [];
    const unit = sortedData[0]?.unit || "";
    sortedData.forEach((item, index) => {
        const levelInfo = levels[index] || { name: `等级 ${item.warning_level}`, color: '#606266' };
        const nextItem = sortedData[index + 1];
        let text = ""; let rangeKey = ""; const threshold1 = item.value; let threshold2;
        if (nextItem) {
        threshold2 = nextItem.value; text = `从 ${threshold1} 到 ${threshold2} ${unit}`;
        } else {
        threshold2 = 1000; text = `大于等于 ${threshold1} ${unit}`;
        }
        rangeKey = `${threshold1}-${threshold2}`;
        const count = pointCounts.value[rangeKey];
        ranges.push({
        name: levelInfo.name, color: levelInfo.color, text: text,
        count: count !== undefined ? count : null,
        });
    });
    return ranges.reverse();
});

const open = async () => {
    visible.value = true;
    displacementData.value = [];
    pointCounts.value = {};
    customThreshold1.value = undefined;
    customThreshold2.value = undefined;
    customQueryRecords.value = [];
    customQueryTriggered.value = false;
    try {
        const response = await axios.get(`/get_monitoring_threshold/`);
        const allData: Threshold[] = response.data.data || [];
        displacementData.value = allData.filter(item => item.threshold_type === "Displacement");
        if (displacementData.value.length > 0) {
            const sortedData = [...displacementData.value].sort((a, b) => a.value - b.value);
            const countPromises = sortedData.map((item, index) => {
                const nextItem = sortedData[index + 1];
                const threshold1 = item.value;
                let threshold2;
                if (nextItem) { threshold2 = nextItem.value; } else { threshold2 = 1000; }
                return axios.get(`/get_displacement_analysis/${threshold1}/${threshold2}/`).then(res => {
                    pointCounts.value[`${threshold1}-${threshold2}`] = res.data.data;
                });
            });
            await Promise.all(countPromises);
        }
    } catch (error) {
        console.error("分析位移数据或获取监测点数量出错:", error);
    }
};

const handleCustomQuery = async () => {
    if (customThreshold1.value === undefined || customThreshold2.value === undefined) {
        ElMessage.warning('请输入完整的阈值范围！');
        return;
    }
    if (customThreshold1.value > customThreshold2.value) {
        ElMessage.error('起始阈值不能大于结束阈值！');
        return;
    }
    isCustomQueryLoading.value = true;
    customQueryRecords.value = [];
    customQueryTriggered.value = true;
    try {
        const response = await axios.get(`/get_displacement_analysis_show/${customThreshold1.value}/${customThreshold2.value}/`);
        customQueryRecords.value = response.data;
    } catch (error) {
        console.error("自定义查询出错:", error);
        ElMessage.error('查询失败，请检查网络或联系管理员。');
    } finally {
        isCustomQueryLoading.value = false;
    }
};

const handleExport = () => {
  if (customQueryRecords.value.length === 0) {
    ElMessage.info('没有可导出的数据。');
    return;
  }
  const headerMap = {
    data_id: '编号', timestamp: '时间', x: 'X坐标', y: 'Y坐标',
    z: 'Z坐标', delta_x: 'ΔX', delta_y: 'ΔY', delta_z: 'ΔZ',
    vector: '位移量', velocity: '速度', acceleration: '加速度', quality_flag: '质量标识'
  };
  const headers = Object.values(headerMap);
  const dataKeys = Object.keys(headerMap);
  const data = customQueryRecords.value.map(record => {
    return dataKeys.map(key => record[key as keyof MonitoringRecord]);
  });
  const exportData = [headers, ...data];
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.aoa_to_sheet(exportData);
  XLSX.utils.book_append_sheet(workbook, worksheet, '监测点数据');
  XLSX.writeFile(workbook, '监测点数据详情.xlsx');
};

const close = () => {
    visible.value = false;
};

defineExpose({ open, close });
</script>

<style scoped>
.warning-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.grid-item {
  flex: 1;
  min-width: calc(50% - 10px);
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 15px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.grid-item-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.level-indicator {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  margin-right: 10px;
  flex-shrink: 0;
}
.level-name {
  font-weight: bold;
  font-size: 16px;
}
.level-range {
  color: #333;
}
.point-count {
  margin-left: 10px;
  color: #606266;
  font-style: italic;
}
.custom-query-form {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}
.custom-query-form .separator {
  margin: 0 5px;
}
.result-count {
  font-weight: bold;
  font-size: 16px;
}
.custom-query-result-container {
  margin-top: 15px;
}
.custom-query-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f4f4f5;
  border-radius: 4px;
}
.custom-query-result {
  color: #606266;
}
.result-table {
  margin-top: 15px;
}
</style>